#coding:utf-8
import urllib,urllib2,json
from urllib2 import HTTPError
import hashlib,traceback

auth_url = "https://www.google.com/accounts/ClientLogin"
subs_url = "https://www.google.com/reader/api/0/subscription/list"
tags_url = "https://www.google.com/reader/api/0/tag/list"
rss_url = "https://www.google.com/reader/api/0/stream/contents/"

class GReader:
    
    auth,sid = None,None
    def doAuth(self,account,passwd):
        print "doauth..."
        params = {"accountType":"HOSTED_OR_GOOGLE",
                  "Email":account,
                  "Passwd":passwd,
                  "service":"reader",
                  "source":"J-ebook-1.0"}
        req = urllib2.Request(auth_url,data=urllib.urlencode(params))
        req.add_header("User-agent", 'Mozilla/5.0')
        req.add_header("Content-Type", 'application/x-www-form-urlencoded')
        try:
            resp = urllib2.urlopen(req)
            arrs =  resp.getcode()==200 and resp.read().split("\n")
            for arr in arrs:
                if arr:
                    it = arr.split('=')
                    if it[0] == "Auth":self.auth =  it[1]
                    if it[0] == "SID":self.sid =  it[1]
                if self.auth and self.sid:
                    print 'auth ok'
                    break
        except HTTPError, e:
            print 'auth error %s' % e.msg
        finally:
            print 'auth done'

    def doGet(self,url,params):
        print 'start request...'
        nurl = "%s?%s"%(url,urllib.urlencode(params))
        req = urllib2.Request(nurl)
        req.add_header("User-agent", 'Mozilla/5.0')
        req.add_header("Authorization", "GoogleLogin auth="+self.auth)
        req.add_header("Cookie","SID="+self.sid)
        try:
            resp = urllib2.urlopen(req)
            return resp.getcode()==200 and resp.read() or ''
        except HTTPError, e:
            print 'request error %s' % e.msg
            return ''
        finally:
            print 'request done'
            
    def doPost(self,url,params):
        print 'start request...'
        req = urllib2.Request(url,data=urllib.urlencode(params))
        req.add_header("User-agent", 'Mozilla/5.0')
        req.add_header("Authorization", "GoogleLogin auth="+self.auth)
        req.add_header("Content-Type", 'application/x-www-form-urlencoded')
        req.add_header("Cookie","SID="+self.sid)
        try:
            resp = urllib2.urlopen(req)
            return resp.getcode()==200 and resp.read() or ''
        except HTTPError, e:
            print 'request error %s' % e.msg
            return ''
        finally:
            print 'request done'

    def loadTags(self,cache=True):
        try:
            return json.loads(open("./cache/tags.json").read())
        except:
            traceback.print_exc()
        result =  self.doGet(tags_url,{'output':'json'})
        if cache:
            with open("./cache/tags.json",'wb') as fb:
                fb.write(result)
        return json.loads(result)
    
    
    def loadSubs(self,cache=True):
        try:
            return json.loads(open("./cache/subs.json").read())
        except :
            traceback.print_exc()

        result = self.doGet(subs_url,{'output':'json'})
        if cache:
            with open("./cache/subs.json",'wb') as fb:
                fb.write(result)
        return json.loads(result)
        

    def loadRss(self,id,cache=True):
        try:
            fname = hashlib.md5(id).hexdigest()
            return json.loads(open("./cache/%s.json"%fname).read())
        except:
            result = self.doGet(rss_url+id,{'output':'json'})
            if cache:
                with open("./cache/%s.json"%fname,'wb') as fb:
                    fb.write(result)
            return json.loads(result)   
        
        
        
        